package cn.lucky.springcloud.controller;

import cn.lucky.springcloud.entities.CommonResult;
import cn.lucky.springcloud.entities.Payment;
import cn.lucky.springcloud.service.ConsumerOrderService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author lingpeng.jiang
 * @create 2021-02-03-22:48
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerOrderController {


    @Value("${server.port}")
    private String serverPort;
    private static final String PAYMENT_URL = "http://cloud-payment-service";

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/payment/{id}")
    @SentinelResource(value = "paymentById",blockHandler = "blockHandle")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        CommonResult forObject = restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        if (forObject.getData() == null){
            throw new RuntimeException("没有找到记录，空指针 ");
        }
        return  forObject;
    }


//    public CommonResult<Payment> fallbackHandle(@PathVariable Long id,Throwable e){
//        CommonResult<Payment> objectCommonResult = new CommonResult<>();
//        objectCommonResult.setCode(400);
//        objectCommonResult.setMessage("当前系统忙,请稍后再重试 java 异常熔断  " + e.getMessage());
//        objectCommonResult.setData(null);
//        return objectCommonResult;
//    }

    public CommonResult<Payment> blockHandle(Long id, BlockException e){
        CommonResult<Payment> objectCommonResult = new CommonResult<>();
        objectCommonResult.setCode(400);
        objectCommonResult.setMessage("当前系统忙,请稍后再重试,sentinel 熔断 :  " + e.getMessage());
        objectCommonResult.setData(null);
        return objectCommonResult;
    }


    @Resource
    private ConsumerOrderService consumerOrderService;

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> feignTest(@PathVariable("id") Long id){
        return consumerOrderService.getPayment(id);
    }













    @GetMapping("/port")
    public String getPort(){
        return serverPort;
    }


}
